<script setup lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import { useRouter, useRoute } from "vue-router";
import { useStore } from "vuex";
// 导入消息工具
import message from "@/utils/message.js";
// 导入图标工具
import { ArrowLeft } from "@/utils/icons.js";
import { getResumeList, submitResume } from "@/api/resume";

// 定义简历类型接口
interface Resume {
    id: string;
    title: string;
    [key: string]: any;
}

// 定义职位类型接口
interface Job {
    id: string;
    title: string;
    company: string;
    salary: string;
    location: string;
    [key: string]: any;
}

const router = useRouter();
const route = useRoute();
const store = useStore();

// 根据URL参数获取简历ID
const resumeIdFromQuery = computed(() => route.query.resumeId as string);

// 表单数据
const submitForm = reactive({
    resumeId: resumeIdFromQuery.value || "",
    jobId: "",
    coverLetter: "",
});

// 表单规则
const rules = reactive({
    resumeId: [{ required: true, message: "请选择要投递的简历", trigger: "change" }],
    jobId: [{ required: true, message: "请选择要投递的职位", trigger: "change" }],
});

// 简历列表 - 明确类型
const resumeList = ref<Resume[]>([]);

// 职位列表 (模拟数据)
const jobList = ref<Job[]>([
    { id: "1", title: "前端开发工程师", company: "科技有限公司", salary: "15k-25k", location: "上海" },
    { id: "2", title: "Web前端工程师", company: "互联网科技公司", salary: "20k-30k", location: "北京" },
    { id: "3", title: "资深前端开发", company: "网络科技有限公司", salary: "25k-35k", location: "广州" },
    { id: "4", title: "Vue开发工程师", company: "软件科技有限公司", salary: "18k-28k", location: "深圳" },
    { id: "5", title: "全栈开发工程师", company: "科技有限公司", salary: "20k-35k", location: "杭州" },
]);

// 选中的职位
const selectedJob = computed(() => {
    return jobList.value.find((job) => job.id === submitForm.jobId) || null;
});

// 选中的简历
const selectedResume = computed(() => {
    return resumeList.value.find((resume: any) => resume.id === submitForm.resumeId) || null;
});

// 加载状态
const loading = ref(false);
const submitting = ref(false);

// 表单引用
const formRef = ref<any>(null);

// 获取简历列表
const getResumes = async () => {
    loading.value = true;
    try {
        // 尝试从Vuex获取
        if (store.state.resume && store.state.resume.resumeList && store.state.resume.resumeList.length > 0) {
            // 使用类型断言避免类型错误
            resumeList.value = store.state.resume.resumeList as Resume[];
        } else {
            // 否则从API获取
            const response = await getResumeList({ status: "1" }); // 只获取已完成的简历
            if (response.code === 200 || response.code === 0) {
                resumeList.value = response.data.list || response.data || [];
            } else {
                message.error("获取简历列表失败");
            }
        }

        // 如果没有简历数据，提供一些模拟数据用于演示
        if (resumeList.value.length === 0) {
            resumeList.value = [
                { id: "1", title: "前端开发工程师简历" },
                { id: "2", title: "实习生应聘简历" },
                { id: "3", title: "校园招聘简历模板" },
            ];
        }

        // 如果URL中有简历ID但不在列表中，需要获取详细信息
        if (resumeIdFromQuery.value && !resumeList.value.find((resume: any) => resume.id === resumeIdFromQuery.value)) {
            // 这里应该调用获取简历详情的API
            // 简化处理，直接添加一个预设值
            resumeList.value.push({ id: resumeIdFromQuery.value, title: "预选简历" });
        }
    } catch (error) {
        console.error("获取简历列表失败", error);
        message.error("获取简历列表失败");
    } finally {
        loading.value = false;
    }
};

// 提交简历
const handleSubmit = async () => {
    if (!formRef.value) return;

    try {
        await formRef.value.validate();

        // 二次确认
        message
            .confirm(
                `确定要将简历"${selectedResume.value?.title}"投递到"${selectedJob.value?.title}"职位吗？`,
                "确认投递",
                {
                    confirmButtonText: "确定投递",
                    cancelButtonText: "取消",
                    type: "info",
                }
            )
            .then(async () => {
                submitting.value = true;
                try {
                    // 调用投递API
                    const response = await submitResume({
                        resumeId: submitForm.resumeId,
                        jobId: submitForm.jobId,
                        coverLetter: submitForm.coverLetter,
                    });

                    if (response.code === 200 || response.code === 0) {
                        message.success("简历投递成功");
                        router.push({
                            path: "/user/submitHistory",
                        });
                    } else {
                        message.error(response.message || "简历投递失败");
                    }
                } catch (error) {
                    console.error("简历投递失败", error);
                    message.error("简历投递失败，请稍后重试");
                } finally {
                    submitting.value = false;
                }
            })
            .catch(() => {});
    } catch (error) {
        console.error("表单验证失败", error);
    }
};

// 返回
const goBack = () => {
    router.go(-1);
};

// 查看简历详情
const viewResume = (id: string) => {
    router.push({
        path: "/user/resumeInfo",
        query: { id },
    });
};

onMounted(() => {
    getResumes();
});
</script>

<template>
    <div class="submit-resume-container" v-loading="loading">
        <div class="page-header">
            <el-button link @click="goBack" :icon="ArrowLeft">返回</el-button>
            <h2>投递简历</h2>
        </div>

        <el-card class="submit-card">
            <el-form ref="formRef" :model="submitForm" :rules="rules" label-width="100px" class="submit-form">
                <el-form-item label="选择简历" prop="resumeId">
                    <el-select v-model="submitForm.resumeId" placeholder="请选择简历" style="width: 100%">
                        <el-option
                            v-for="resume in resumeList"
                            :key="resume.id"
                            :label="resume.title"
                            :value="resume.id"
                        />
                    </el-select>
                    <div class="resume-actions" v-if="submitForm.resumeId">
                        <el-button type="text" @click="viewResume(submitForm.resumeId)">查看简历</el-button>
                    </div>
                </el-form-item>

                <el-form-item label="选择职位" prop="jobId">
                    <el-select
                        v-model="submitForm.jobId"
                        placeholder="请选择要投递的职位"
                        style="width: 100%"
                        filterable
                    >
                        <el-option
                            v-for="job in jobList"
                            :key="job.id"
                            :label="`${job.title} - ${job.company}`"
                            :value="job.id"
                        >
                            <div class="job-option">
                                <div class="job-title">{{ job.title }}</div>
                                <div class="job-company">{{ job.company }}</div>
                                <div class="job-info">
                                    <span>{{ job.salary }}</span>
                                    <span class="job-location">{{ job.location }}</span>
                                </div>
                            </div>
                        </el-option>
                    </el-select>
                </el-form-item>

                <!-- 如果选择了职位，显示职位详情 -->
                <div v-if="selectedJob" class="job-details">
                    <el-card shadow="never">
                        <template #header>
                            <div class="job-header">
                                <h3>{{ selectedJob.title }}</h3>
                                <div class="job-company">{{ selectedJob.company }}</div>
                            </div>
                        </template>
                        <div class="job-info-details">
                            <div class="info-item">
                                <span class="info-label">薪资范围：</span>
                                <span class="info-value">{{ selectedJob.salary }}</span>
                            </div>
                            <div class="info-item">
                                <span class="info-label">工作地点：</span>
                                <span class="info-value">{{ selectedJob.location }}</span>
                            </div>
                        </div>
                    </el-card>
                </div>

                <el-form-item label="求职信">
                    <el-input
                        v-model="submitForm.coverLetter"
                        type="textarea"
                        :rows="6"
                        placeholder="请简要介绍您对该职位的理解和期望（可选）"
                    />
                </el-form-item>

                <el-form-item class="submit-actions">
                    <el-button @click="goBack">取消</el-button>
                    <el-button
                        type="primary"
                        @click="handleSubmit"
                        :loading="submitting"
                        :disabled="!submitForm.resumeId || !submitForm.jobId"
                    >
                        投递简历
                    </el-button>
                </el-form-item>
            </el-form>
        </el-card>
    </div>
</template>

<style scoped>
.submit-resume-container {
    max-width: 900px;
    margin: 0 auto;
    padding: 20px;
}

.page-header {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
}

.page-header h2 {
    margin: 0 0 0 10px;
}

.submit-card {
    margin-bottom: 20px;
}

.submit-form {
    max-width: 100%;
}

.resume-actions {
    margin-top: 8px;
    text-align: right;
}

.job-option {
    padding: 5px 0;
}

.job-title {
    font-weight: bold;
}

.job-company {
    font-size: 14px;
    color: #606266;
}

.job-info {
    font-size: 13px;
    color: #909399;
    display: flex;
    justify-content: space-between;
    margin-top: 5px;
}

.job-location {
    color: #67c23a;
}

.job-details {
    margin: 15px 0;
}

.job-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.job-header h3 {
    margin: 0;
}

.job-info-details {
    color: #606266;
}

.info-item {
    margin-bottom: 8px;
}

.info-label {
    display: inline-block;
    width: 80px;
    color: #909399;
}

.submit-actions {
    display: flex;
    justify-content: center;
    margin-top: 30px;
}

@media screen and (max-width: 768px) {
    .job-header {
        flex-direction: column;
        align-items: flex-start;
    }

    .job-header .job-company {
        margin-top: 5px;
    }
}
</style>
